package user_logic

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"github.com/golang-jwt/jwt/v4"
	"golang.org/x/crypto/bcrypt"
	"time"

	"yunzhan/api-server/internal/svc"
	"yunzhan/api-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

type LoginInfo struct {
	ID       int    `json:"id"`
	Username string `json:"username"`
	Password string `json:"password"`
	Role     string `json:"role"`
}

// NewLoginLogic 用户登录
func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginRequest) (resp *types.LoginResponse, err error) {
	// 验证输入数据
	if req.Username == "" || req.Password == "" {
		return &types.LoginResponse{
			Code:    500,
			Message: "用户名和密码不能为空"}, fmt.Errorf("用户名和密码不能为空")
	}

	// 判断使用的数据库类型
	flag := l.svcCtx.Config.UseMysql

	var query string
	if flag {
		query = fmt.Sprintf("SELECT id, username, password, role FROM %s WHERE username = ? AND deleted_at IS NULL",
			l.svcCtx.Config.Mysql.Tables.UserInfoTable)
	} else {
		query = fmt.Sprintf("SELECT id, username, password, role FROM %s WHERE username = ? AND deleted_at IS NULL",
			l.svcCtx.Config.SQLite.Tables.UserInfoTable)
	}

	var user LoginInfo

	err = l.svcCtx.Conn.QueryRow(&user, query, req.Username)
	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return &types.LoginResponse{
				Code:    500,
				Message: "用户不存在"}, fmt.Errorf("用户不存在")
		}
		return nil, fmt.Errorf("failed to query user: %v", err)
	}

	// 验证密码
	err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Password))
	if err != nil {
		return &types.LoginResponse{
			Code:    500,
			Message: "无效的用户名或密码"}, fmt.Errorf("无效的用户名或密码")
	}

	// 生成 JWT 令牌
	token, err := generateToken(user.ID, user.Username, l.svcCtx.Config.Auth.AccessSecret)
	if err != nil {
		return nil, fmt.Errorf("failed to generate token: %v", err)
	}

	return &types.LoginResponse{
		Code:    200,
		Message: "用户登录成功",
		Token:   token}, nil
}

func generateToken(userId int, username string, secret string) (string, error) {
	claims := make(jwt.MapClaims)
	claims["exp"] = time.Now().Add(time.Second * time.Duration(86400)).Unix()
	claims["iat"] = time.Now().Unix()
	claims["userId"] = userId
	claims["username"] = username

	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(secret))
}
